package cn.jsu.oj.judgment.net.netHandler;


import cn.jsu.oj.judgment.factory.CmdHandleFactory;
import cn.jsu.oj.judgment.factory.JudgeFactory;
import cn.jsu.oj.judgment.handle.CommandPack;
import cn.jsu.oj.judgment.net.starter.JudgeStarter;
import cn.jsu.oj.judgment.net.starter.ServiceStarter;
import cn.jsu.oj.judgment.pojo.AbstractPack;
import cn.jsu.oj.judgment.satellite.util.SpringUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Objects;

import static cn.jsu.oj.judgment.config.DataStructureConfig.messageQueue;

/**
 * 数据
 */
@Slf4j
@ChannelHandler.Sharable
@Component("judgeClientHandler")
public class JudgeClientHandler extends ChannelInboundHandlerAdapter {

    public static Channel channel;


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channel = ctx.channel();
        ServiceStarter.judgeActiveSign = true;
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        AbstractPack abstractPack = (AbstractPack) msg;
        if (abstractPack.getTypeNo() != 92) {
            if (! ServiceStarter.judgeVerifySign) {
                super.channelRead(ctx,msg);
                return;
            }
        }
        handle(msg);
        super.channelRead(ctx, msg);
    }

    private void handle(Object msg) throws InterruptedException {
        AbstractPack pack = (AbstractPack) msg;
        short typeNo = pack.getTypeNo();

        //如果包类型为 89 通知包   12判题任务包  38任务数量应答包

        if (typeNo == 89 || typeNo == 21 || typeNo==12) {
            messageQueue.put(pack);
            return;
        }

        CommandPack<?> commandPack = new CommandPack<>(channel, pack);
        CmdHandleFactory.getHandle(pack.getTypeNo()).handle(commandPack);
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        channel.close();
        ServiceStarter.judgeActiveSign = false;
        ServiceStarter.judgeVerifySign = false;
        JudgeFactory judgeStarterFactory = (JudgeFactory) SpringUtil.getBean("judgeStarterFactory");
        ((JudgeStarter) Objects.requireNonNull(judgeStarterFactory).getProduct((short) 97)).start();
        ((JudgeStarter) Objects.requireNonNull(judgeStarterFactory).getProduct((short) 99)).start();
        super.channelInactive(ctx);
    }
}
